'use strict'
//引用model
let { users } = require('../model');
const auth = require('../utile/auth');

//显示登录页面
let login = async (cxt, next) => {
    cxt.render('login.html', { msg: '' });
};
//处理登录请求
let login_fn = async (cxt, next) => {
    let uid = cxt.request.body.username || '';   //trim()去除字符串两边的空格
    let pad = cxt.request.body.password || '';

    let ts = '';
    if (uid.length > 0 && pwd.length > 0) {
        let row = await users.findOne({
            where: {
                username: uid,
                password: pad
            }
        });
        let u2Json = JSON.stringify(row);    //stringify()转换字符串
        if (u2Json !== 'null') {
            cxt.session.usersId = row.id;
            cxt.session.userName = row.username;
            ts = { code: 200, msg: '登录成功' };
        } else {
            ts = { code: 1000, msg: '用户名或密码错误，请确认后重试' };
        }
    } else {
        ts = { code: 1000, msg: '用户名和密码不能为空' };
    }
    cxt.body = JSON.stringify(ts);
}

module.exports = {
    '/login': ['get', auth, login],
    '/login_fn': ['post', login_fn]
}